/**
 * 可升降吊具(EMS)
 */
export default {
  start: function(self, ctx) {
    const CIRCLE = 'pCircle';
    const circle = `${self.getParameter(CIRCLE)}`;
    const name = this.mapping(circle);
    self.ems = {
      circle: circle,
      name: name,
    };

    // 初始化 EMS
    this.initEMS(self, ctx);
  },
  onParameterUpdate: function(self, ctx, key, value) {
    const PROGRESS = 'pProgress';
    const CIRCLE = 'pCircle';

    // 处理环号变化
    if (key === CIRCLE && value != self.ems.circle) {
      self.ems.circle = `${value}`;
      self.ems.name = this.mapping(self.ems.circle);
      this.initEMS(self, ctx);
      return;
    }

    // 处理动画播放进度
    if (key === PROGRESS) {

      // 检测 Animation 存在
      if (!self.ems || !self.ems.mixer) {
        return;
      }

      // 处理进度
      const progress = parseFloat(value);
      if (typeof progress !== 'number') {
        return;
      }

      const mixer = self.ems.mixer;
      const clip = self.ems.clip;
      const action = self.ems.action;

      // 显示 EMS
      self.visible = true;

      // 更新动画播放进度
      action.time = clip.duration * this.between(progress, 0, 1);
      action.play();
      mixer.update(1);

      // 根据动画混合器结果, 更新对象位置.
      mixer._bindings.forEach(prop => {
        const binding = prop.binding;
        const attribute = this.getAttribute(binding.path);
        const property = binding.resolvedProperty;
        if (attribute === 'position') {
          self.position.copy(property);
        }
        if (attribute === 'quaternion') {
          self.rotation.setFromQuaternion(property);
        }
        if (attribute === 'scale') {
          self.scale.copy(property);
        }
      });

      // 停止动画混合
      action.stop();
    }
  },
  between: function (value, min, max) {
    return Math.min(Math.max(value, min), max);
  },
  getAttribute: function(path) {
    if (!path) {
      return null;
    }
    const parts = path.split('.');
    return parts[parts.length - 1];
  },
  mapping: function(circle) {
    if (circle) {
      // 一环
      if (['1','2','3','4','5'].indexOf(circle) >= 0) {
        return 'Action';
      }
      // 二环
      if (['6','7','8','9'].indexOf(circle) >= 0) {
        return 'Action';
      }
    }
    return null;
  },
  initEMS: function(self, ctx) {
    const AnimationMixer = HaloEngine.Three.AnimationMixer;
    const mixer = new AnimationMixer(self.group);
    const clip = self.getAnimation(self.ems.name);

    // 隐藏 EMS
    self.visible = false;
    if (clip) {
      const action = mixer.clipAction(clip);
      action.pause = true;

      // 更新 EMS 参数
      self.ems.mixer = mixer;
      self.ems.clip = clip;
      self.ems.action = action;
    }
  }
}
